package com.ysl.netty.client;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ysl.common.utils.DateUtils;
import com.ysl.framework.web.domain.AjaxResult;
import com.ysl.netty.domain.SentBody;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.HashMap;
import java.util.Map;

public class DemoClient {

    public static Channel channel;

    public static void start()
    {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = null;
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new MyClientInitializer());
            //与对应的url建立连接通道
            channelFuture = bootstrap.connect("localhost", 8899).sync();
            //channelFuture.channel().closeFuture().sync();
        }
        catch (Exception ex)
        {

        }finally {
            eventLoopGroup.shutdownGracefully();
        }
        channel = channelFuture.channel();
    }

	public static void main(String[] args) throws Exception {

        /*
        HashMap<String,Object> paramMap=new HashMap<String,Object>();
        String username=DateUtil.currentSeconds()+"";
        paramMap.put("username", username);
        paramMap.put("password","1234");
        System.out.println(username);

        String res = HttpUtil.post("http://127.0.0.1:8080/api", paramMap, 60000);
        JSONObject json=JSONObject.parseObject(res);
        if(json.getInteger("code")==0)
        {
            //启动客户端
            start();
            //发送登录信息
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("type","login");
            jsonObject.put("key",username);
            String msg=JSONObject.toJSONString(jsonObject);

            channel.writeAndFlush(msg);
        }
        else
        {
            System.out.println("登录失败");
        }
        */

        //启动客户端
        start();
    }
}
